import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  DeviceEventEmitter,
} from "react-native";
import { 
  Button,  
  Provider,
  Toast,
  WhiteSpace,
  WingBlank,
  Modal,
  Badge,
  List
} from "@ant-design/react-native";

import Icon from "react-native-vector-icons/AntDesign";
import { Tabs } from "@ant-design/react-native";

import Goods from "./Goods";
const config = require('../service/config')
const request = require('../service/request')

const Dimensions = require("Dimensions");
const { width } = Dimensions.get("window");

// var arrs = require("./test.json");

export default class BasicTabsExample extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      checked: false,
      visible2:false,
      allWine:[],
      orderobj:{},
      total:0,//总价
      num:0//酒数量
    }
    this.onClose2 = this.onClose2.bind(this)
    this.addWine = this.addWine.bind(this)
    this.successToast = this.successToast.bind(this)
  }
  componentWillUnmount =() =>{
    this.setState = (state,callback)=>{
      return;
    };
    DeviceEventEmitter.removeAllListeners('navigatorBack');
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }
  componentDidMount(){
    let url = config.api.base + config.api.winedata
    let newarr = []
    // let allWine = this.state.allWine
    request.get(url).then(res => {
      // console.log(res.data)
      if(res.code == 'ok'){
        
        // console.log(typeof(res.data))
        let arrs = res.data
        for(let i=0;i<arrs.length;i++){
          newarr.push(arrs[i])
        }
        // allWine.push(res.data)
        // allWine 
        console.log(newarr)
        this.setState({
          allWine:newarr
        })
      }else{
        alert('获取酒信息错误 index.js')
      }

    })
    .catch(err => {
      console.log(err)
    })
  
  }
  
  onClose2 = () => {
    this.setState({
      visible2: false,
    });
  };
  clearWine = () => {
    Modal.alert('确定要清空吗', '清空购物车', [
      { text: '确定', onPress: () => {
        let allWine = this.state.allWine
        for(let i=0;i<allWine.length;i++){
          allWine[i].count = 0
        }
        this.setState({
          allWine:allWine,
          num:0,
          total:0,
        })
      }},
      {
        text: '返回',
        onPress: () => console.log('cancel'),
        style: 'cancel',
      }
    ]);
  }
  plusWine = (val) => {
    console.log(val)
   let allWine = this.state.allWine
   let total = this.state.total
   let total1
   console.log(allWine,total)
   let num = this.state.num + 1
   for(let i=0;i<allWine.length;i++){
     if(val == allWine[i].id){
       allWine[i].count = allWine[i].count + 1;
       total1 = total + 1*allWine[i].price;     
       break;
     }
   }
   this.setState({
     allWine:allWine,
     total:total1,
     num:num,
   })
  }
  minusWine = (val) => {
    console.log(val)
    let allWine = this.state.allWine
    let total = this.state.total
    let num = this.state.num - 1
    let total1
    for(let i=0;i<allWine.length;i++){
     if(val == allWine[i].id){
       allWine[i].count = allWine[i].count - 1
       total1 = total - 1*allWine[i].price
       break;
     }
   }
   this.setState({
     allWine:allWine,
     total:total1,
     num:num
   })
  }
  // componentWillUnmount() {
   
  // }
  addWine = (val) => {
    let self = this
    console.info(val)
    let num = this.state.num
    let total = this.state.total
    let allWine = this.state.allWine
    console.log('a',allWine)
    let total1 = 0
    // console.log(newobj)
    for(let i=0;i<allWine.length;i++){
      if(val.id == allWine[i].id){
        allWine[i].count += 1 
        // console.log(allWine[i].price)
        //计算总价
        total1 = total + 1*allWine[i].price
      }
    }
    self.setState({
      num:num+1,
      allWine:allWine,
      total:total1
    })
  }
  successToast = (tableid,tabletext) => {
    // alert(tableid)
    let url = config.api.base + config.api.orderadd
    let allWine = this.state.allWine
    let allWine2 = []
    let data = []
    let total = this.state.total
    let self = this
    let time = self.formatDateTime()

    for(let i=0;i<allWine.length;i++){
      if(allWine[i].count != 0){
        allWine[i].tableid = tableid
        allWine[i].date = time
        allWine[i].status = 0
        allWine[i].num = allWine[i].count
        allWine[i].total = total
        allWine[i].wineid = allWine[i].id
        delete allWine[i].id
        allWine2.push(allWine[i])
      }
    }
    for(let i=0;i<allWine2.length;i++){
      data.push(allWine2[i])
    }
    
    // console.log(2,allWine2)
    console.log(3,allWine2)
    console.log(4,data)
    if(allWine2.length == 0){
      Toast.info('亲 你还没有选择商品哦 !!!',3)
      return;
    }
    // let data = allWine2
    Modal.alert('请确认支付',`共 ${this.state.total} 元`, [
      { text: '确定', onPress: () => {
       // alert(tableid)
        this.props.navigation.navigate('Order', {
        tableid: tableid,
        tabletext:tabletext,
        allWine:allWine2,
        total:total,
        time:time
        });
        request.post(url,{
          data
        }).then(res => {
          if(res.code == 'ok'){
            console.log(res.msg)
            console.log('1')
          }else{
            console.log(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
      }
    
    },
      {
        text: '返回',
        onPress: () => {},
        style: 'cancel',
      }
    ]);

    
  }
  formatDateTime = () => {
    let date = new Date();
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let minute = date.getMinutes();
    // let second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    // second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute;
    };
   
  render() {
    // console.log('1',this.state.allWine)
    // console.log(this.state.total)
    const tabs = [
      { title: "白酒" },
      { title: "葡萄酒" },
      { title: "洋酒" },
      { title: "啤酒" },
      { title: "其他" }
    ];
    const style = {
      alignItems: "center",
      flex: 1,
      width: width,
      backgroundColor: "#F5FCFF"
    };
    const { navigation } = this.props;
    const tableid = navigation.getParam('tableid', 'null');
    const tabletext = navigation.getParam('tabletext', 'null');
    return (
      <Provider>
      <View style={styles.container}>
        <View style={styles.header}>
          <Icon name='enviromento' size={16}></Icon>
          <Text style={{fontSize:16,marginLeft:5,fontWeight:'bold'}}>你所在位置：</Text>
          {/* <Text style={{fontSize:20,color:'#74b9ff'}}>{tableid}</Text> */}
          <Text style={{fontSize:20,color:'#74b9ff'}}>{tabletext}</Text>
        </View>
        <View style={styles.body}>
          <Tabs tabs={tabs}>
            <View style={style}>
              <Goods addWine={this.addWine.bind(this)} kindid='1'/>
            </View>
            <View style={style}>
              <Goods addWine={this.addWine.bind(this)} kindid='2'/>
            </View>
            <View style={style}>
              <Goods addWine={this.addWine.bind(this)} kindid='3'/>
            </View>
            <View style={style}>
             <Goods addWine={this.addWine.bind(this)} kindid='4'/>
            </View>
            <View style={style}>
            <Goods addWine={this.addWine.bind(this)} kindid='5'/>
            </View>
          </Tabs>
          <View style={styles.bottomNavBar}>
            <View style={styles.bottomNavBarIcon}>
            <Badge text={this.state.num}>
              <TouchableOpacity onPress={() => this.setState({ visible2: true })}>
                <Image
                  source={require("../../image/箱子.png")}
                  style={{ width: 50, height: 50 }}
                />
              </TouchableOpacity>
              </Badge>
              <Text style={{ color: "#fff", fontSize: 24, fontWeight: "bold" }}>
                ￥ {this.state.total}
              </Text>
            </View>
            <Button
              type="primary"
              onPress={() => this.successToast(tableid,tabletext)}
              style={{ width: width / 3, borderRadius: 0 }}
            >
              立即结算
            </Button>
          </View>
        </View>
      </View>

      <Modal
          popup
          visible={this.state.visible2}
          animationType="slide-up"
          onClose={this.onClose2}
          style={{flex:1}}
        >
        <WhiteSpace></WhiteSpace>
        {/* <WhiteSpace></WhiteSpace> */}
          <WingBlank size='md'>
            <List renderHeader={'订单'}>
            {
              this.state.allWine.map((item,index) => {
                if(item.count == 0){
                  return null
                }else{
                  return(
                    < List.Item thumb={item.img}  key={index}>
                      {item.name}
                      <View style={{width:300,height:45,flexDirection:'row',alignItems:'center',justifyContent:'space-around'}}>
                        <TouchableOpacity onPress={() => this.minusWine(item.id)}>
                          <Icon name ='minuscircleo' size={22} color='#3498db'></Icon>
                        </TouchableOpacity>
                          <Text style={{fontSize:18,color:'#e74c3c'}}>{item.count} 🍺 </Text>
                        <TouchableOpacity onPress={() => this.plusWine(item.id)}>
                          <Icon name ='pluscircleo' size={22} color='#3498db'></Icon>
                        </TouchableOpacity>
                        <Text style={{fontSize:15,color:'#ccc'}}>{item.price}/瓶</Text>
                        <View style={{flexDirection:'row',alignItems:'center'}}>
                          <Icon name='pay-circle-o1' size={16}></Icon>
                          <Text style={{fontSize:18,color:'#e74c3c',marginLeft:5}}>{item.count * item.price}</Text>
                        </View>
                        </View>
                      </List.Item>
                  )
                }
              })
            }
            </List>
            <List renderHeader={'总计'}>
              <List.Item extra={<View><Text>{this.state.num}🍺</Text></View>}>
              <View style={{flexDirection:'row',alignItems:'center'}}>
                <Icon name='pay-circle-o1' size={16}></Icon>
                <Text style={{fontSize:20,color:'red',marginLeft:5}}>{this.state.total}</Text>
              </View>
             
              </List.Item>
            </List>
          </WingBlank>
          <WingBlank size='md'>
          <View style={{flexDirection:'row',justifyContent:'space-around'}}>
          
          <TouchableOpacity type="warning" onPress={this.clearWine} style={{borderRadius:3,width:width/2,height:50,alignItems:'center',justifyContent:"center"}}>
            <Icon name='delete' size={20}></Icon>
            <Text style={{fontSize:10,marginTop:3}}>清空购物车</Text>
          </TouchableOpacity>
          <TouchableOpacity type="primary" onPress={this.onClose2} style={{borderRadius:3,width:width/2,height:50,alignItems:'center',justifyContent:"center"}}>
            <Icon name='logout' size={20}></Icon>
            <Text style={{fontSize:10,marginTop:3}}>返回</Text>
          </TouchableOpacity>
          </View>
         
        </WingBlank>
        </Modal>
      </Provider>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5FCFF",
    alignItems: "center"
  },
  header: {
    height: width / 6.5,
    width: width / 1.03,
    backgroundColor: "#F5FCFF",
    alignItems: "center",
    justifyContent: "center",
    flexDirection: "row",
    position: "absolute"
  },
  body: {
    marginTop: width / 6.5,
    flex: 1
  },
  bottomNavBar: {
    width: width,
    height: 47,
    backgroundColor: "rgba(60,60,60,0.8)",

    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-end"
  },
  bottomNavBarIcon: {
    flexDirection: "row",
    width: width / 1.5,
    justifyContent: "space-around",
    alignItems: "center"
  },
  a:{
    height:100
  }
});
